package com.lastproject.ejb.util;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.EmailGroupDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.entities.EmailGroup;
import com.lastproject.ejb.entities.User;

@Stateless
@LocalBean
public class EmailGroupConversion {

	@PersistenceContext
	EntityManager em;

	@EJB
	UserConversion uconv;

	public EmailGroupConversion() {

	}

	public EmailGroupDTO fromEntity(EmailGroup g) {
		EmailGroupDTO groupDTO = new EmailGroupDTO();
		groupDTO.setId(g.getId());
		groupDTO.setName(g.getName());
		List<UserDTO> userDTOs = new ArrayList<UserDTO>();

		for (User u : g.getUsers()) {
			userDTOs.add(uconv.fromEntity(u));
		}
		groupDTO.setUsers(userDTOs);

		return groupDTO;
	}

	public EmailGroup fromDTO(EmailGroupDTO groupDTO) {

		EmailGroup group = em.find(EmailGroup.class, groupDTO.getId());
		
		if (group == null) {
			group = new EmailGroup();
		}

		group.setName(groupDTO.getName());
		group.setUsers(null);
		List<User> users = new ArrayList<User>();

		if (groupDTO.getUsers() != null) {
			for (UserDTO uDTO : groupDTO.getUsers()) {
				users.add(uconv.fromDTO(uDTO));
			}
			group.setUsers(users);
		}
		
		return group;

	}
}
